<template>
  <div class="createorder">
    <ContentBox title="确认订单" :fixed="true" :ostyle="style">
      <template slot="oleft"><van-icon color="#000000" name="arrow-left"/></template>
    </ContentBox>
    <notice :top="$remToPx('0.88')" class="not"></notice>
    <div class="order_address" v-if="!ruzf">
      <div class="address_info" @click="toMyAddress">
        <van-icon name="location" size=".42rem" color="#999999" class="icon_location"/>
        <span class="noaddress" v-if="addressInfo && !addressInfo.id">添加收货地址</span>
        <div class="haveaddress" v-else>
          <div class="address_name">
            <span>{{addressInfo.real_name}}</span>
            <p>{{addressInfo.phone}}</p>
          </div>
          <div class="address_content">{{addressInfo.province}} {{addressInfo.city}} {{addressInfo.district}} {{addressInfo.detail}}</div>
        </div>
        <van-icon name="arrow" size=".42rem"/>
      </div>
    </div>
    <div class="cart_contant" v-if="!ruzf">
      <div class="cart_shop">
        <div class="cart_shop_header">
          <van-icon name="shop" size=".33rem"/>
          <span class="shop_name">{{cartDetail.product_info && cartDetail.product_info.merchant.name}}</span>
          <!-- <van-icon name="arrow" size=".24rem"/> -->
        </div>
      </div>
      <div class="cart_item">
        <div class="item_detail">
          <div class="item_msg">
            <img :src="$img('logo.png')">
            <div class="msg_right">
              <p class="van-multi-ellipsis--l2">{{cartDetail.product_attr_detail && cartDetail.product_info.store_name}}</p>
              <div><span>{{cartDetail.product_attr_detail && cartDetail.product_attr_detail.suk}}</span></div>
            </div>
            <div class="item_price">
              <span>￥{{cartDetail.product_attr_detail && cartDetail.product_attr_detail.price}}</span>
              <p>X{{cartDetail.cart_num}}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="discount">
    <!-- 平台优惠 -->
    </div>
    <div class="pay_type">
      <p>支付方式</p>
      <van-radio-group v-model="radio">
        <div class="pay yue" @click="radio = 'yue'">
          <van-icon :name="$img('yuepay.png')" size=".64rem"/>
          <span>余额支付</span>
          <van-radio name="yue" checked-color="#E0261B"></van-radio>
        </div>
        <div class="pay alipay" @click="radio = 'alipay'" v-if="!$isWxBrowser()">
          <van-icon :name="$img('alipay.png')" size=".64rem"/>
          <span>支付宝支付</span>
          <van-radio name="alipay" checked-color="#1880bd"></van-radio>
        </div>
        <div class="pay wechat" @click="radio = 'wechatApp'">
          <van-icon :name="$img('wxpay.png')" size=".64rem"/>
          <span>微信支付</span>
          <van-radio name="wechatApp" checked-color="#008000"></van-radio>
        </div>
      </van-radio-group>
    </div>
    <van-submit-bar
      v-if="wxid !== ''"
      :price="wxprice * 100"
      button-text="立即支付"
      @submit="onSubmit"
    />
    <van-submit-bar
      v-else
      :price="(cartDetail.product_attr_detail && cartDetail.product_attr_detail.price) * (cartDetail.cart_num) * 100"
      button-text="立即支付"
      @submit="onSubmit"
    />
    <van-overlay :show="passwordShow" :z-index="3000">
      <div class="passwordcancel" @click="passwordcancel">
        <van-icon name="cross" size=".64rem" color="#ffffff"/>
      </div>
      <van-password-input
        :value="password"
        info="请输入 6 位数密码"
        :focused="showKeyboard"
        :gutter="10"
        @focus="showKeyboard = true"
        class="inpPassWord"
      />
      <van-number-keyboard
        :show="showKeyboard"
        @input="onInput"
        @delete="onDelete"
        @blur="showKeyboard = false"
      />
    </van-overlay>
    <van-overlay :show="loadingShow" class="loading" z-index="4000">
      <van-loading size="2.4rem" :vertical="true"></van-loading>
    </van-overlay>
  </div>
</template>

<script>
export default {
  data () {
    return {
      style: {
        background: '#ffffff',
        color: '#000'
      },
      cartDetail: {},
      addressInfo: '',
      addid: '',
      checked: '',
      radio: 'yue',
      password: '',
      showKeyboard: false,
      passwordShow: false,
      orderid: '',
      loadingShow: false,
      alipayType: '',
      ruzf: false,
      wxid: '',
      wxprice: ''
    }
  },
  watch: {
    password (val) {
      if (val.length === 6) {
        this.showKeyboard = false
        this.passwordShow = false
        this.loadingShow = true
        this.orderPay(this.wxid === '' ? this.orderid : this.wxid, val, 'weixinh5').then(res => {
          if (res.status === 200) {
            this.loadingShow = false
            this.$toast.success('支付成功')
            if (this.$route.query.pinkId || this.$route.query.pinkId > -1) {
              this.$router.replace('/shopOrder?showView=1')
            } else if (this.wxid !== '') {
              this.$router.replace('/join')
            } else {
              this.$router.replace('/shopOrder?showView=2')
            }
          }
        })
      }
    }
  },
  methods: {
    onSubmit () {
      if (this.addid === '' && this.ruzf === false) {
        this.$toast('请选择收货地址')
        return false
      }
      if (this.radio === 'yue' && this.$store.state.uifo.has_payment_pwd === 'NO') {
        this.$dialog.confirm({
          title: '提示',
          message: '当前账户尚未设置支付密码',
          confirmButtonText: '去设置'
        }).then(_ => {
          this.$router.push('/paypwd')
        })
        return false
      }
      if (this.wxprice !== '') {
        if (this.radio === 'yue' && (this.wxprice) > this.$store.state.uifo.now_money) {
          this.$toast('余额不足')
          return false
        }
      } else {
        if (this.radio === 'yue' && (this.cartDetail.product_attr_detail.price * this.cartDetail.cart_num) > this.$store.state.uifo.now_money) {
          this.$toast('余额不足')
          return false
        }
      }
      this.loadingShow = true
      if (this.ruzf === true) {
        if (this.radio === 'yue') {
          this.showKeyboard = true
          this.passwordShow = true
        } else {
          if (this.$store.state.pl === 'ANDROID') {
            AndroidJsBridge.toPay(this.wxid, this.radio === 'alipay' ? 2 : 1)
          } else if (this.$store.state.pl === 'IOS') {
            window.iosCallHandler('toPay', {
              uni: this.wxid,
              paytype: this.radio === 'alipay' ? '2' : '1'
            })
          } else if (this.$store.state.pl === 'H5') {
            if (!this.$isWxBrowser()) {
              this.$toast('请使用微信浏览器进行该操作')
              return false
            }
            this.orderPay(this.wxid, '', 'weixin').then(res => {
              if (res.status === 200) {
                this.$wxChooseWXPay(res.data.result.jsConfig).then(res => {
                  if (res.err_msg === 'get_brand_wcpay_request:ok') {
                    this.loadingShow = false
                    this.$toast.success('支付成功')
                    this.$router.replace('/join')
                  } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                    this.loadingShow = false
                    this.$toast.success('支付已取消')
                  } else {
                    this.loadingShow = false
                    this.$toast.success('支付失败')
                  }
                })
              }
            })
          }
        }
      } else {
        this.computedOrder(this.$route.query.orderKey).then(_ => {
          this.createOrder(this.$route.query.orderKey).then(res => {
            this.orderid = res.data.result
            if (this.radio === 'yue') {
              this.showKeyboard = true
              this.passwordShow = true
            } else {
              if (this.$store.state.pl === 'ANDROID') {
                AndroidJsBridge.toPay(this.orderid, this.radio === 'alipay' ? 2 : 1)
              } else if (this.$store.state.pl === 'IOS') {
                window.iosCallHandler('toPay', {
                  uni: this.orderid,
                  paytype: this.radio === 'alipay' ? '2' : '1'
                })
              } else if (this.$store.state.pl === 'H5') {
                if (!this.$isWxBrowser()) {
                  this.$toast('请使用微信浏览器进行该操作')
                  return false
                }
                this.orderPay(this.orderid, '', 'weixin').then(res => {
                  if (res.status === 200) {
                    this.$wxChooseWXPay(res.data.result.jsConfig).then(res => {
                      if (res.err_msg === 'get_brand_wcpay_request:ok') {
                        this.loadingShow = false
                        this.$toast.success('支付成功')
                        if (this.$route.query.pinkId || this.$route.query.pinkId > -1) {
                          this.$router.replace('/shopOrder?showView=1')
                        } else {
                          this.$router.replace('/shopOrder?showView=2')
                        }
                      } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                        this.loadingShow = false
                        this.$toast.success('支付已取消')
                      } else {
                        this.loadingShow = false
                        this.$toast.success('支付失败')
                      }
                    })
                  }
                })
              }
            }
          })
        })
      }
    },
    getShopCartDetail (id) {
      this.$axios.get(`/api/cart/${id}`).then(res => {
        if (res.status === 200) {
          this.cartDetail = res.data
          if (!this.$route.query.addressid) {
            this.addid = this.cartDetail.userAddressInfo.id ? this.cartDetail.userAddressInfo.id : ''
            this.addressInfo = this.cartDetail.userAddressInfo
          }
        }
      })
    },
    toMyAddress () {
      this.$router.push({ name: 'myAddress', query: { id: this.$route.query.id, orderKey: this.$route.query.orderKey } })
    },
    setAddress (id) {
      this.$axios.get(`api/address/detail/${id}`).then(res => {
        if (res.status === 200) {
          this.addressInfo = res.data
        }
      })
    },
    computedOrder (orderKey) {
      return new Promise(resolve => {
        this.$axios.post(`/api/order/computed/${orderKey}`).then(res => {
          if (res.status === 200) {
            resolve(res)
          } else {
            this.loadingShow = false
            this.$dialog({ message: res.msg })
          }
        })
      })
    },
    createOrder (orderKey) {
      return new Promise(resolve => {
        this.$axios.post(`/api/order/create/${orderKey}`, {
          addressId: this.addid,
          real_name: this.addressInfo.real_name,
          phone: this.addressInfo.phone,
          useIntegral: 0,
          couponId: 0,
          payType: 'yue',
          shipping_type: 1,
          from: 'weixinh5',
          pinkId: this.$route.query.pinkId ? this.$route.query.pinkId : '',
          combinationId: this.$route.query.combinationId ? this.$route.query.combinationId : ''
        }).then(res => {
          if (res.status === 200) {
            resolve(res)
          } else {
            this.loadingShow = false
            this.$dialog({ message: res.msg })
          }
        })
      })
    },
    orderPay (orderid, psw, from) {
      return new Promise(resolve => {
        this.$axios.post('/api/order/pay', {
          uni: orderid,
          paytype: this.radio === 'wechatApp' ? 'wechat' : 'yue',
          from: from,
          payment_pwd: psw
        }).then(res => {
          if (res.status === 200) {
            resolve(res)
          } else {
            this.loadingShow = false
            this.$dialog({ message: res.msg })
          }
        })
      })
    },
    onInput (key) {
      this.password = (this.password + key).slice(0, 6)
    },
    onDelete () {
      this.password = this.password.slice(0, this.password.length - 1)
    },
    passwordcancel () {
      this.password = ''
      this.showKeyboard = false
      this.passwordShow = false
    },
    payCallBack (success) {
      this.loadingShow = false
      if (success === '1') {
        this.$toast.success('支付成功')
        if (this.$route.query.pinkId || this.$route.query.pinkId > -1) {
          this.$router.replace('/shopOrder?showView=1')
        } else if (!this.$route.query.pinkId && this.$route.query.pinkId <= -1) {
          this.$router.replace('/shopOrder?showView=2')
        } else if (this.wxid !== '') {
          this.$router.replace('/join')
        }
      } else {
        this.$toast.success('支付已取消')
      }
    }
  },
  created () {
    if (this.$route.query.wxid) {
      this.ruzf = true
      this.wxid = this.$route.query.wxid
      this.wxprice = parseFloat(this.$route.query.price)
    } else {
      this.getShopCartDetail(this.$route.query.id)
      if (this.$route.query.addressid) {
        this.addid = this.$route.query.addressid
        this.setAddress(this.$route.query.addressid)
      }
    }
  },
  mounted () {
    if (this.$store.state.pl === 'ANDROID') {
      window.payCallBack = success => {
        this.loadingShow = false
        if (success) {
          this.$toast.success('支付成功')
          if (this.$route.query.pinkId || this.$route.query.pinkId > -1) {
            this.$router.replace('/shopOrder?showView=1')
          } else if (this.wxid !== '') {
            this.$router.replace('.join')
          } else {
            this.$router.replace('/shopOrder?showView=2')
          }
        } else {
          this.$toast.fail('支付已取消')
        }
      }
    } else if (this.$store.state.pl === 'IOS') {
      window.iosRegisterHandler('payCallBack').then(res => {
        this.payCallBack(res)
      })
    }
  }
}
</script>

<style lang="scss">
.createorder{
  height: 100%;
  background: #f6f6f6;
  padding-top: 1.32rem;
  .order_address{
    padding: 0 .16rem 0;
    .address_info{
      width: 100%;
      background: #ffffff;
      border-radius: .08rem;
      display: flex;
      align-items: center;
      padding: .28rem .16rem;
      .icon_location{
        margin-right: .26rem;
      }
      .noaddress{
        flex: 1;
        color: #ff2a1f;
        font-size: .28rem;
      }
      .haveaddress{
        flex: 1;
        display: flex;
        flex-direction: column;
        .address_name{
          display: flex;
          align-items: flex-end;
          span{
            margin-right: .16rem;
            font-size: .28rem;
            color: #333333;
          }
          p{
            color: #999999;
            font-size: .24rem;
          };
        }
        .address_content{
          color: #333333;
          font-size: .24rem;
          word-break: break-all;
        }
      }
    }
  }
  .cart_contant{
    padding: .16rem;
    .cart_shop{
      border-radius: .16rem .16rem 0 0;
      background: #ffffff;
      padding: .32rem .16rem;
      .cart_shop_header{
        display: flex;
        align-items: center;
        .shop_name{
          color: #333333;
          font-size: .24rem;
          margin: 0 .16rem 0 .1rem;
          font-weight: bold;
        }
      }
    }
    .cart_item{
      border-radius: 0 0 .16rem .16rem;
      display: flex;
      font-size: .24rem;
      align-items: center;
      padding: .16rem .38rem .16rem .16rem;
      background: #ffffff;
      .item_detail{
        margin-left: .16rem;
        width: 100%;
        .item_msg{
          display: flex;
          margin-bottom: .1rem;
          border-radius: .08rem;
          img{
            width: 1.8rem;
            height: 1.8rem;
            border-radius: .16rem;
            margin-right: .24rem;
            flex: 0 1 auto;
          }
          .msg_right{
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            flex: 1;
            div{
              max-width: 2.98rem;
              height: .48rem;
              border-radius: .24rem;
              background: #f0f0f0;
              color: #999999;
              line-height: .48rem;
              text-align: center;
              display: flex;
              padding: 0 .16rem;
              align-items: center;
              justify-content: center;
              span{
                margin-right: .1rem;
              }
            }
          }
        }
        .item_price{
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          flex: 0 1 auto;
          span{
            color: #fe0000;
            font-size: .28rem;
            font-weight: 700;
          }
        }
      }
      ._check{
        width: .32rem;
        height: .32rem;
        border-radius: .32rem;
      }
    }
  }
  .van-submit-bar__button{
    width: 3.2rem;
  }
  .pay_type{
    margin: .16rem;
    padding: .16rem .32rem .16rem .16rem;
    background: #ffffff;
    border-radius: .08rem;
    &>p{
      font-size: .28rem;
      color: #333333;
    }
  }
  .pay{
    font-size: .28rem;
    display: flex;
    align-items: center;
    margin: .24rem 0 .34rem;
    &>span{
      margin-left: .24rem;
      flex: 1;
    }
  }
  .payBtn{
    width: calc(100% - .48rem);
    margin: 1rem auto .24rem;
    background: #E0261B;
    color: #ffffff;
    text-align: center;
    font-size: .56rem;
    border-radius: .16rem;
    height: .88rem;
    line-height: .88rem;
  }
  .inpPassWord{
    margin-top: 50%;
  }
  .passwordcancel{
    padding: .36rem;
  }
  .loading{
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2100 !important;
    .van-loading__text{
      font-size: .36rem;
      font-weight: bold;
    }
  }
  .not{
    position: fixed;
    top: .88rem;
    left: 0;
  }
}
</style>
